export function fetchSSEStream({
  url,
  params,
  onMessage,
  onError,
  onComplete,
}: {
  url: string
  params: Record<string, any>
  onMessage: (msg: string) => void
  onError?: (err: any) => void
  onComplete?: () => void
}) {
  const query = new URLSearchParams(params).toString()
  const eventSource = new EventSource(`${url}?${query}`)

  eventSource.onmessage = (event) => {
    if (event.data === '[DONE]') {
      eventSource.close()
      onComplete && onComplete()
      return
    }
    onMessage(event.data)
  }
  eventSource.onerror = (err) => {
    eventSource.close()
    onError && onError(err)
  }
  return eventSource
}
